package org.balabala.user.service.impl;

import io.micrometer.core.instrument.util.TimeUtils;
import lombok.extern.log4j.Log4j;

import org.balabala.user.utils.Query;
import org.balabala.user.dao.UserDao;
import org.balabala.user.entity.UserEntity;
import org.balabala.user.service.UserService;
import org.balabala.user.utils.PageUtils;
import org.balabala.user.utils.Resp;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import sun.util.calendar.BaseCalendar;

import javax.xml.crypto.Data;


@Log4j
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public Resp login(UserEntity userEntity) {
        String phoneNumber = userEntity.getPhoneNumber();
        String passWord = userEntity.getPassword();

        if(phoneNumber == null || passWord == null){
            return Resp.error(500,"用户名或密码不能为空");
        }else{
            UserEntity user = this.baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("phone_number", phoneNumber));
            if(user == null){
                return Resp.error(500,"用户名不存在");
            }else{
                //如果用户名存在，验证密码是否正确
                BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
                boolean matches = passwordEncoder.matches(passWord,user.getPassword());
                System.out.println(matches);
              //  $2a$10$e3VAbKwfZ15E..R34MpCy.myJxXSXww90GHJgt8xlj6ahysxCATFO
                if(matches){
                    user.setPassword(null);
                    return  Resp.ok().put("data",user);
                }else {
                    return  Resp.error(500,"请输入正确密码");
                }
            }
        }
    }

    @Transactional
    @Override
    public Resp register(UserEntity userEntity) {
        List<UserEntity> phone_number = this.baseMapper.selectList(new QueryWrapper<UserEntity>().eq("phone_number",userEntity.getPhoneNumber()));
        if(phone_number.size() != 0){
            return Resp.error(500,"该手机号已被注册");
        }else {
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //  System.out.println("password:"+userEntity.getPassword());
            String encode = passwordEncoder.encode(userEntity.getPassword());
            // System.out.println(encode);
            userEntity.setPassword(encode);
            userEntity.setUid(System.currentTimeMillis());
            userEntity.setRegistrationTime(new Date());
            userEntity.setIsMember(0);
            userEntity.setState(0);
            int insert = this.baseMapper.insert(userEntity);
            if(insert == 1){
                return Resp.ok();
            }else {
                return Resp.error(500,"注册失败，稍后重试");
            }
        }
    }

    @Override
    public List<UserEntity> selectListByUids(List<Long> ids) {
        List<UserEntity> userEntities = this.baseMapper.selectBatchIds(ids);
        return userEntities;
    }

    @Override
    public UserEntity selectByUid(Long uid) {
        UserEntity userEntity = this.baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("uid", uid));
        userEntity.setPassword(null);

        return userEntity;
    }

    //模糊查询
    @Override
    public PageUtils selectByKeyword(HashMap<String, Object> hashMap) {
        String keyword = (String)hashMap.get("keyword");
        Integer state = (Integer)hashMap.get("state");
        if(keyword.equals("")){
            IPage<UserEntity> page = this.page(
                    new Query<UserEntity>().getPage(hashMap),
                    new QueryWrapper<UserEntity>().eq("state",state)
            );
            List<UserEntity> collect = page.getRecords().stream().map(item -> {
                item.setPassword(null);
                return item;
            }).collect(Collectors.toList());
            page.setRecords(collect);
            return new PageUtils(page);
        }else{
            try {
                //进行模糊查询
                IPage<UserEntity> page = this.page(
                        new Query<UserEntity>().getPage(hashMap),
                        new QueryWrapper<UserEntity>()
                                .eq("state",state)
                                .and(item -> item.like("user_name",keyword).or().like("mailbox",keyword))
                );
                List<UserEntity> collect = page.getRecords().stream().map(item -> {
                    item.setPassword(null);
                    return item;
                }).collect(Collectors.toList());
                page.setRecords(collect);
                return new PageUtils(page);
            }catch (Exception e){
                return null;
            }

        }


    }

    @Transactional
    @Override
    public boolean banByIds(Long[] asList,Integer state) {
        Boolean bool = true;
        for (Long integer : asList) {
            try {
                UserEntity userEntity = new UserEntity();
                userEntity.setUid(integer);
                userEntity.setState(state);
                this.baseMapper.update(userEntity,new QueryWrapper<UserEntity>().eq("id",integer));
            }catch (Exception e){
                bool = false;
            }
        }
        return bool;

    }

}